package com.tz.marlon.web.admin;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tz.marlon.bean.Blog;
import com.tz.marlon.bean.TzParams;
import com.tz.marlon.bean.User;
import com.tz.marlon.dao.admin.IAdminBlogDao;

@RequestMapping("/admin")
@Controller
public class AdminControlller {

	@Autowired
	private IAdminBlogDao adminBlogDao;
	
	@RequestMapping("/index")
	public String index(){
		return "admin/index";
	}
	
	@RequestMapping("/add")
	public String add(){
		return "admin/add";
	}
	
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable("id")Integer id){
		ModelAndView modelAndView = new ModelAndView();
		HashMap<String, Object> blog = adminBlogDao.mapById(id);
		modelAndView.addObject("blog", blog);
		modelAndView.setViewName("admin/add");
		return modelAndView;
	}
	
	@ResponseBody
	@RequestMapping("/loadData")
	public ModelAndView loadData(TzParams params){
		ModelAndView modelAndView = new ModelAndView();
		params.setStatus(1);
		params.setIsDelete(1);
		List<HashMap<String, Object>> blogs = adminBlogDao.listMaps(params);
		int itemsCount = adminBlogDao.count(params);
		modelAndView.setViewName("admin/template");
		modelAndView.addObject("blogs",blogs);
		modelAndView.addObject("itemsCount",itemsCount);
		return modelAndView;
	}
	
	@ResponseBody
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public String saveBlog(HttpSession session,Blog blog){
		User user = (User)session.getAttribute("user");
		blog.setHits(0);
		blog.setUserId(user.getId());
		blog.setIsDelete(1);
		blog.setStatus(1);
		blog.setComments(0);
		adminBlogDao.save(blog);
		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String updateBlog(Blog blog){
		try {
			adminBlogDao.update(blog);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public String deleteBlog(Blog blog){
		try {
			blog.setIsDelete(0);
			adminBlogDao.update(blog);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	
}
